package cn.jhz.learn.community_dynamic.manager;

import cn.jhz.learn.community_dynamic.common.exception.SMSException;
import cn.jhz.learn.community_dynamic.common.util.UniversalUtil;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;

import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.Optional;

@Service
public class SMSManager {

  private final IAcsClient client;

  public SMSManager() {
	this.client = new DefaultAcsClient(
	    DefaultProfile.getProfile("cn-hangzhou", "LTAI4G5zMLmV8tNAHBJSEkSf", "UGyPlnDZBxxNGv0WPzLmtTtcyQmSYh"));
  }

  private Optional<String> sendSms(String phoneNumbers, String templateCode, String code) {
  	CommonRequest request = new CommonRequest();
	request.setSysMethod(MethodType.POST);
	request.setSysDomain("dysmsapi.aliyuncs.com");
	request.setSysVersion("2017-05-25");
	request.setSysAction("SendSms");
	request.putQueryParameter("RegionId", "cn-hangzhou");
	request.putQueryParameter("SignName", "MACHINE005");
	request.putQueryParameter("PhoneNumbers", phoneNumbers);
	request.putQueryParameter("TemplateCode", templateCode);
	request.putQueryParameter("TemplateParam", code);
	try {
	  CommonResponse response = this.client.getCommonResponse(request);

	  // TODO: 短信服务异常情况处理
	  return Optional.of(response.getData());
	} catch (ServerException e) {
	  e.printStackTrace();
	} catch (ClientException e) {
	  e.printStackTrace();
	}
	return Optional.empty();
  }

  public String sendLoginVerification(String phoneNumbers, String code) {
	return sendSms(phoneNumbers, "SMS_195720768", "{\"code\": " + code + "}").get();
  }

  public String sendRegisterVerification(String phoneNumbers, String code) {
	return sendSms(phoneNumbers, "SMS_195870040", "{\"code\": " + code + "}").get();
  }

  public void sendGeneralVerification(String phoneNumbers, String code) {
	String result = sendSms(phoneNumbers, "SMS_195860416", "{\"code\": " + code + "}").get();
	Map<String, Object> resultMap = UniversalUtil.parseResult(result);
	if (!resultMap.get("Code").equals("OK"))
	  /* 发送失败 */
	  throw new SMSException(result);
  }
}
